import { defineStore } from 'pinia'
import { ref } from 'vue'
import { fetchPermission, ident, getOperationPermissions } from '@/api/user'
import router, { DynamicRoute, addRoutes } from '@/router/index'
// import { userGetInfoService } from '../../api/user'
// 用户模块 token setToken removeToken
export const useUserStore = defineStore(
  'storeUser',
  () => {
    const user = ref({})
    const getUser = () => {
      return user.value
    }
    const setUser = (obj) => {
      user.value = obj
    }
    const removeUser = () => {
      user.value = {
        userName: '',
        account: '',
        permission: '',
        email: '',
        jobNumber: '',
        avatar:''
      }
    }
    const token = ref('')
    const getToken = async () => {
      return token.value
    }
    const setToken = (newToken) => {
      token.value = newToken
    }
    const removeToken = () => {
      token.value = ''
    }
    const setUserName = (name) => {
      user.value.userName = name
    }
    const getUserName = () => {
      return user.value.userName
    }
    const getPermission = () => {
      return user.value.permission
    }
    const getAccount = () => {
      return user.value.account
    }
    const getEmail = () => {
      return user.value.email
    }
    const getJobNumber = () => {
      return user.value.jobNumber
    }
    const role = ref([])
    const getRole = () => {
      return role.value
    }
    const setRole = (obj) => {
      role.value = obj
    }
    const removeRole = () => {
      role.value = []
    }
    const permissions = ref([])
    const getPermissions = () => {
      return permissions.value
    }
    const setPermissions = (obj) => {
      permissions.value = obj
    }
    // 验证token是否有效
    const identification = async () => {
      const res = await ident() //向后台请求验证
      return res.data
    }
    // 生成动态路由
    const FETCH_PERMISSION = async () => {
      // 确保只添加一次动态路由
      if (!router.hasRoute('Home')) {
        const permission = getPermission()
        const res = await fetchPermission({ permission }) //向后台请求权限路由
        if (res.data.code == 300) {
          ElMessage({
            dangerouslyUseHTMLString: true,
            message: `<strong style="font-size:1.5rem">${res.data.msg},关闭返回登录</strong>`,
            showClose: true,
            duration: 0,
            onClose: () => {
              // 清除本地的数据 (token + user信息)
              removeToken()
              removeRole()
              removeUser()
              router.removeRoute('Home') // 移除动态路由
              setUserName('未登录')
              router.push('/login')
            }
          })
        } else {
          setRole(res.data.data)
        }
        let res2 = await getOperationPermissions()
        if (res2.data.code == 300) {
          permissions.value = []
        } else {
          permissions.value = res2.data.data
        }
        //选择home
        const homeRoute = DynamicRoute.filter((v) => v.path === '/')[0]
        //判断是否找到相应父路由
        if (homeRoute) {
          //判断是否有children
          if (!homeRoute.children) homeRoute.children = []
          // 遍历获取的路由数据，递归生成新的多级路由
          addRoutes(homeRoute.children, role.value)
          router.addRoute(homeRoute)
          // console.log('All routes:', router.getRoutes())
          return true
        }
      }
      return false
    }
    return {
      token,
      getToken,
      setToken,
      removeToken,
      user,
      getUser,
      setUser,
      removeUser,
      setUserName,
      getUserName,
      getPermission,
      getAccount,
      getEmail,
      getJobNumber,
      role,
      getRole,
      setRole,
      removeRole,
      permissions,
      getPermissions,
      setPermissions,
      FETCH_PERMISSION,
      identification
    }
  },
  {
    persist: true
  }
)
